package com.longchat.controller.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.longchat.domain.permission.Resource;
import com.longchat.domain.permission.SysUser;
import com.longchat.dto.system.LoginInfo;
import com.longchat.service.inter.system.IPermissionService;
import com.longchat.service.inter.system.ISysuserService;
import com.longchat.utils.Constant;
import com.longchat.utils.MD5Util;
import com.longchat.utils.vo.ResultWrapper;

@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController{

	@Autowired
	private ISysuserService sysUserService;
	@Autowired
	private IPermissionService permissionService;
	@RequestMapping("")
	public String loginPage(){
		return "/admin/login";
	}
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		session.removeAttribute(Constant.SESSION_USER);
		return "/admin/login";
	}
	@ResponseBody
	@RequestMapping("/login")
	public ResultWrapper<String> login(LoginInfo info,ModelMap map,HttpSession session)
	{
		info.setPassword(MD5Util.md5Hex(info.getPassword()));
		SysUser user = sysUserService.login(info);
		if(user==null){
			return new ResultWrapper<String>().CustomStatus(401, "用户名密码不正确");
		}else{
			List<Resource> permissionRes = permissionService.findPermissinsByUserName(user.getUserName());
			session.setAttribute(Constant.SESSION_USER, user);
			List<String> codes = new ArrayList<String>();
			List<String> urls = new ArrayList<String>();
			for(Resource r:permissionRes){
				codes.add(r.getCode());
				urls.add(r.getUrl());
			}
			session.setAttribute(Constant.PERMISSION_URLS, codes);
			session.setAttribute(Constant.PERMISSSION_CODES, urls);
		}
		return new ResultWrapper<String>().OK();
	}
	@RequestMapping("/index")
	public String index(ModelMap map,HttpSession session){
		map.put("navibars", permissionService.findNavibars(getUser(session).getUserName()));
		return "/admin/index";
	}
}
